<template>
  <div>
    <el-tag
      v-for="(tag,index) in tags"
      :key="tag.name"
      class="ksd-mx-1"
      closable
      :type="tag.type"
      @close="handleRemoveTags(index)"
    >
      {{ tag.name }}
    </el-tag>
    <el-input v-model.trim="inputTag" style="margin-top: 10px;" maxlength="20" placeholder="请输入课程标签" @blur="handleAddTags" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Ksd from '@/utils/index.js'

const emits = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: [Object, String]
  },
})

const inputTag = ref('')
const tags = ref([])
const tagsColor = ref(['success', 'info', 'warning', 'danger'])

// 生命周期执行函数
onMounted(() => {
  const tagsList = props.modelValue.split(',')
  if (tagsList.length > 0) {
    tagsList.forEach((item, index) => {
      tags.value.push({ name: item, type: tagsColor.value[index % 4] })
    })
  }
})

// 添加标签到数组中
const handleAddTags = () => {
  if (!inputTag.value) {
    Ksd.error('请输入标签内容')
    return
  }

  if (tags.value.length >= 4) {
    Ksd.error('标签最多添加4个！')
    return
  }

  const index = tags.value.findIndex(c => c.name === inputTag.value)
  if (index === -1) {
    // 添加到标签列表中
    tags.value.push({ name: inputTag.value, type: tagsColor.value[tags.value.length % 4] })
    emits('update:modelValue', tags.value.map(c => c.name).join(','))
    // 把输入清空掉
    inputTag.value = ''
  } else {
    Ksd.error('该【' + inputTag.value + '】标签已经存在列表中了....')
  }
}

// 删除标签
const handleRemoveTags = (index) => {
  tags.value.splice(index, 1)
  emits('update:modelValue', tags.value && tags.value.length > 0 ? tags.value.map(c => c.name).join(',') : '')
}

</script>

<script>

export default {
  name: 'UploadImage',
  methods: {

  }
}
</script>

<style lang="scss" scoped>
.ksd-mx-1{
  margin-right:5px;
}
</style>
